<!--
* @Description: historyTrack.vue 历史轨迹回放
* @Author: 王燕欣
* @Date: 2024-10-07 11:08
-->
<template>
  <div class="public_container">
    <!-- 地图区域 -->
    <div id="mapTrack" class="ku_map_container"></div>
    <!-- 车辆查询信息 -->
    <div class="ku_header_container">
      <div class="ku_header_content">
        <div class="">
          <span @click="lineBusShowStateClick">
            <span class="ku_title ku_margin_right_8">{{ trackBusInfo.busShowName||trackBusInfo.busSelfId||'请选择' }}</span>
            <span class="ku_header_select_arrow">
              <van-icon v-if="lineBusShowState" name="arrow-down" color="#4251DF" />
              <van-icon v-else name="arrow-up" color="#4251DF" />
            </span>
          </span>
          <span class="ku_select_date ku_margin_left_50" @click="datePickerPopupClick">{{ queryDateStr }} <i class=""></i></span>
          <span class="ku_select_date ku_margin_left_40" @click="datetimePickerPopupClick">{{ queryTime.start }} 至 {{ queryTime.end }} <i class=""></i></span>
        </div>
        <div class="ku_button ku_button_primary ku_button_small" @click="showOperationalDataClick" v-if="tableData.length>0">运行数据</div>
        <!-- 线路列表 -->
        <div class="ku_vertical_content" v-if="lineBusShowState">
          <div class="ku_vertical_container">
            <div class="ku_vertical_list">
              <div class="ku_vertical_item" @click="selectRouterClick(item.routeId)" v-for="(item,index) in routerList" :key="index" :routerId="item.routeId" :class="item.routeId === trackRouterId?'active':''"> {{item.routeName}} </div>
            </div>
            <!-- 子线列表 -->
            <div class="ku_vertical_container ku_vertical_select_two">

              <!-- 线路下的车辆列表 -->
              <!-- <div class="ku_vertical_container ku_vertical_select_two"> -->
              <div class="ku_vertical_list">
                <template v-if="trackRouterBusList.length>0">
                  <div class="ku_vertical_item" @click="selectBusClick(item.busId)" v-for="item in trackRouterBusList" :key="item.busId" :class="item.busId === trackBusId?'active':''"> {{item.busShowName}} </div>
                </template>
                <van-empty v-else description="暂无车辆信息" />
              </div>
              <!-- </div> -->
            </div>

          </div>
        </div>
      </div>
    </div>
    <DatePickerPopup ref="DatetimePickerRef" @onConfirm="onConfirmDate"></DatePickerPopup>
    <DatetimePickerPopup ref="datetimePickerPopupRef" @onConfirm="datetimeOnConfirm" :currentTime="queryTime"></DatetimePickerPopup>

    <!-- 右侧更多操作处理 -->
    <div class="ku_gis_right_more_operations ku_button_list_inline ">
      <div class="ku_button ku_button_plain_primary" @click="showStationStatusClick">
        显示站点
        <i class="ku_icon_active" v-if="lineVectorLayerConfig.stationStatus"></i>
      </div>
      <div class="ku_button ku_button_plain_primary" @click="showSpeedStatusClick">
        显示速度
        <i class="ku_icon_active" v-if="overlayCtrl.timeSpeedChecked"></i>
      </div>
      <!-- <div class="ku_button ku_button_plain_primary" @click="simulatedSideSearch">
        模拟搜索
      </div> -->

    </div>
    <div class="ku_history_track_legend">
      <span> <i class=""></i>标准轨迹</span>
      <span> <i class="active"></i>实际轨迹</span>
    </div>
    <!-- 控制播放区域 -->
    <div class="ku_history_track_play_progress">
      <div class="ku_history_track_play_progress_content">
        <div class="ku_history_track_play">
          <van-image round width="30px" height="30px" :src="trackPlayer.suspendSrc" v-if="trackPlayer.isPlaying" @click="pauseTrack" />
          <van-image round width="30px" height="30px" :src="trackPlayer.playSrc" v-else @click="playTrack" />
        </div>
        <!-- 播放进度 -->
        <div class="ku_history_track_play_slider">
          <span>
            {{ queryTime.start }}
          </span>
          <van-slider class="ku_history_track_slider" v-model="trackPlayer.currentStep" @change="onChangeSlider" :min="trackPlayer.minStep" :max="trackPlayer.maxStep" bar-height="3px" active-color="#7A90E9">
            <template #button>
              <van-image class="ku_history_track_play_slider_button" round width="23px" height="23px" :src="trackPlayer.sliderSrc" />
            </template>
          </van-slider>
          <span>
            {{ queryTime.end }}
          </span>
        </div>
        <div class="ku_history_track_speed" @click="playSpeedShow=true">
          倍速
          <div>
            {{ trackPlayer.playSpeed }}
          </div>
          <div v-if="playSpeedShow" class="ku_vertical_list_sector ku_history_track_speed_list">
            <div class="ku_vertical_list">
              <div class="ku_vertical_item" :class="item === trackPlayer.playSpeed?'active':''" @click.stop="playSpeedClick(item)" v-for="item in trackPlayer.playSpeeds" :key="item"> {{item}} </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 运行数据 -->
    <TablePopup ref="TablePopupRef" :columns="runningDataColumns" :tableData="tableData"></TablePopup>
    <div class="gis_realtime_monitor_image">
      <img id="realtimeMonitorBusLocatedIcon" :src="vehicleOperatingList.busLocated" />
      <img id="realtimeMonitorBusDirection" :src="vehicleOperatingList.direction" />
      <img id="realtimeMonitorBusPeccancyDirection" :src="vehicleOperatingList.alertDirection" />
      <img id="realtimeMonitorBusIcon" :src="vehicleOperatingList.bus1" />
      <canvas id="canvasSpeed" width="162" height="125"></canvas>
    </div>

  </div>
</template>
<script>
import { Feature } from "ol";
import { LineString, Point } from "ol/geom";
import { Fill, Icon, Stroke, Style, Text } from "ol/style";
import CircleStyle from "ol/style/Circle";

import globalConfigs from "@/utils/globalConfigs";
import FlutterBridge from "@/utils/FlutterBridge";
import $store from '@/store'

import HiMap from "@/plugins/map/himap";
import { Toast } from "vant";
import DatetimePickerPopup from "@/components/DatetimePickerPopup.vue";
import DatePickerPopup from "@/components/DatePickerPopup.vue";
import TablePopup from "@/components/TablePopup.vue";

import playButtonSrc from "@/assets/images/track/progress_play.png";
import suspendButtonSrc from "@/assets/images/track/progress_suspend.png";
import sliderButtonSrc from "@/assets/images/track/progress_slide.png";

import busLocated from "@/assets/images/gis/busLocated.png";
import direction from "@/assets/images/gis/direction.png";
import bus1 from "@/assets/images/gis/bus1.png";
import alertDirection from "@/assets/images/gis/alertDirection.png";

import dayjs from "dayjs";
import { getAuthRouteListApi } from "@/api/base";
import { getHistoryBusListByRouteApi, getRouteStationLineApi } from "@/api/gis/historyTrack";
import {
  getHistoryInfoByBusListApi,
} from "@/api/gis/historyTrack";

export default {
  name: "gisMonitoring",
  components: {
    DatePickerPopup,
    DatetimePickerPopup,
    TablePopup,
  },
  props: {},

  data() {
    return {
      hiMap: null,
      // 轨迹颜色--为多辆车走准备
      busColorList: [
        "#22B722",
        "#F7635C",
        "#31B1EA",
        "#FFAA24",
        "#8A97A9",
        "#E03D7B",
        "#955DFA",
        "#14A063",
        "#93DF0F",
        "#0ECBCD",
      ],
      // canvas 线路上小车车辆图片
      vehicleOperatingList: {
        direction: direction,
        bus1: bus1,
        alertDirection: alertDirection,
        busLocated: busLocated,
      },
      // 图层控制绑定
      overlayCtrl: {
        subLineChecked: false,
        mainLineChecked: false,
        stationChecked: true,
        GPSChecked: true,
        speedLimitChecked: false,
        timeSpeedChecked: true, // 显示速度
        speedVectorLayerObject: {},// 当前速度内容
      },

      mapLayer: {
        trackVectorLayer: null, // 运行轨迹图层
        lineVectorLayer: null, // 线路轨迹图层
        busVectorLayer: null, // 车辆图层
        peccancyVectorLayer: null, // 违规告警图层
        speedVectorLayer: null, // 速度图层
        drawVectorLayer: null, // 绘制图层
        markerVectorLayer: null, // 标记图层
      },
      // 绘制线路地图相关信息
      lineVectorLayerConfig: {
        mainLineColor: "rgba(66, 81, 223, 0.7)", // 主线路颜色
        subLineColor: "rgba(66, 81, 223, 0.7)", // 副线路颜色
        stationStatus: true, // 设置是否显示站点信息
      },
      routeParamState: false, // 路由是否有参数

      lineBusShowState: false, // 选择线路，车辆列表
      routerList: [], // 线路列表
      activeRouterIndex: 0, // 当前选择的线路序号


      trackSubRouteId: '', //当前选择的线路子线id

      routeRelationList: [], // 当前线路站点列表
      tableData: [], // 运行轨迹数据
      runningDataColumns: [
        {
          name: "时间",
          width: 160,
          field: "actDateTime",
        },
        {
          name: "车辆",
          width: 140,
          field: "busShowName",
        },
        {
          name: "驾驶员",
          width: 120,
          field: "driverName",
        },
        {
          name: "速度(公里/小时)",
          width: 200,
          field: "busSpeed",
        },
        {
          name: "信息类型",
          width: 220,
          field: "infoType",
        },
        {
          name: "信息内容",
          width: 320,
          field: "infoContent",
        },
        {
          name: "手动",
          width: 100,
          field: "isManuLoptName",
        },
        {
          name: "线路",
          width: 100,
          field: "routeName",
        },
        {
          name: "补发",
          width: 100,
          field: "isAppendName",
        },
        {
          name: "累计里程(公里)",
          width: 200,
          field: "addGpsMile",
        },
      ], // 运行数据头部筛选

      peccancyList: [], // 违规信息列表

      trackRouterId: "", // 当前选择的线路id
      trackRouterBusList: [], // 当前线路下的车辆列表
      trackBusId: "", // 当前车辆id
      trackBusInfo: {}, // 当前车辆信息；

      peccancyBtnVisible: true, // 违规告警是否显示

      dateShow: false,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(),

      queryDateStr: "", // 查询日期
      queryTime: { start: "", end: "" }, // 查询时间
      startTimeUrl: null,
      endTimeUrl: null,

      playSpeedShow: false, // 倍速选择

      trackPlayer: {
        // 播放进度控制
        busIdList: [],
        isPlaying: false, // 是否播放中
        minStep: 1, // 最小位置
        maxStep: 100, // 最大位置
        stepSecond: 10, // 一步播放多少秒数据
        currentStep: 1, // 当前位置
        currentTime: "", // 当前播放到的时间
        playSpeed: 8, // 播放速度
        alertEvents: {}, // 违规信息
        playInterval: null, // 播放句柄
        playSpeeds: [1, 2, 4, 8, 16, 32, 64, 128],
        playSrc: playButtonSrc, // 播放按钮
        suspendSrc: suspendButtonSrc, // 暂停按钮
        sliderSrc: sliderButtonSrc, // 进度按钮
      },
    };
  },
  watch: {
    '$store.state.user.token': {
      handler(newVal) {
        // console.log('watch--监听-newVal--->store.token---', newVal);
        if (newVal) {
          console.log('token------>', $store.state.user.token);
          this.$nextTick(() => {
            this.pageInit();
            this.initMapLayer();
            this.getAuthRouteListFun(); //
          });

        }
      },
      deep: true, //  深度监听
      immediate: true, // 立即执行
    },
    '$store.state.user.rightSideSearchHistoryTrack': {
      handler(newVal) {
        if (newVal) {
          console.log('rightSideSearchHistoryTrack------>', newVal);
          this.rightSideSearchCallback(newVal);
        }
      },
      deep: true, //  深度监听
      immediate: true, // 立即执行
    },
  },
  mounted() {
    console.log('路由有参数状态---query-', this.$route.query)
    // 有参数状态
    if (this.$route.query.routeId && this.$route.query.busId) {
      this.trackRouterId = this.$route.query.routeId;
      this.trackBusId = this.$route.query.busId;
      this.startTimeUrl = this.$route.query.startTime;
      this.endTimeUrl = this.$route.query.endTime;
      this.routeParamState = true;
      // console.log('路由有参数状态----', this.routeParamState)
    }

    this.hiMap = new HiMap("mapTrack", {});
    if (globalConfigs.IS_DEV) {
      this.$nextTick(() => {
        this.pageInit();
        this.initMapLayer();
        this.getAuthRouteListFun(); //
      });
    } else {
      FlutterBridge.RequestFlutterBridge('getTokenFromFlutter');// 从flutter获取token
      window.FlutterBridgeCallback = FlutterBridge.FlutterBridgeCallback; // 监听flutter回掉方法

    }

  },
  methods: {
    /**
    * @Description: 模拟Flutter 数据 回调方法
    * @Author: 王燕欣
    * @Date: 2025-01-20 14:09
    */
    simulatedSideSearch() {
      let prames = {
        "method": "rightSideSearch",
        "data": {
          "busId": "2000000000000270204",
          "orgId": null,
          "routeIdList": null,
          "routeId": null,
          "cardId": "川AL6390",
          "busSelfId": "028864",
          "busShowStr": "028696|川AL6390",
          "status": null,
          "isTrolleyBus": null,
          "seatCount": null,
          "isSrt": null,
          "useCharacter": null,
          "passengers": null,
          "minimunTrolleyRate": null,
          "productId": null,
          "subCompanyId": null,
          "busCustomType": null,
          "selected": "1"
        },
        "type": "huifang"
      }
      prames = JSON.stringify(prames)
      FlutterBridge.FlutterBridgeCallback(prames)
    },

    /**
    * @Description: flutter 搜索回调事件
    * @Author: 王燕欣
    * @Date: 2025-01-20 17:39
    */

    rightSideSearchCallback(params) {
      try {
        let resData = params.data;
        // console.log('flutter 搜索回调事件-----rightSideSearchCallback---res-', resData);
        this.mapLayer.trackVectorLayer.getSource().clear();
        this.mapLayer.speedVectorLayer.getSource().clear();
        this.mapLayer.busVectorLayer.getSource().clear();

        this.trackPlayer.currentStep = 0;
        this.trackBusId = resData.busId;
        this.trackPlayer.busIdList = [resData.busId];

        this.lineBusShowState = false; // 关闭选择车辆
        this.trackBusInfo = resData;
        // console.log('选择车辆事件---车辆详情', this.trackBusInfo);
        this.getHistoryInfoByBusList();

      } catch (error) {
        console.error('flutter 搜索回调事件---rightSideSearchCallback----', error)

      }
    },

    initMapLayer() {
      if (!this.mapLayer.lineVectorLayer) {
        this.mapLayer.lineVectorLayer = this.hiMap.createUserLayer(
          "line",
          {},
          {}
        );
      }
      if (!this.mapLayer.trackVectorLayer) {
        this.mapLayer.trackVectorLayer = this.hiMap.createUserLayer(
          "track",
          {},
          {}
        );
      }
      if (!this.mapLayer.speedVectorLayer) {
        this.mapLayer.speedVectorLayer = this.hiMap.createUserLayer(
          "speed",
          {},
          {}
        );
      }
      if (!this.mapLayer.busVectorLayer) {
        this.mapLayer.busVectorLayer = this.hiMap.createUserLayer(
          "bus",
          {},
          {}
        );
      }
      if (!this.mapLayer.peccancyVectorLayer) {
        this.mapLayer.peccancyVectorLayer = this.hiMap.createUserLayer(
          "peccancy",
          {},
          {}
        );
      }
      // if (!this.mapLayer.drawVectorLayer) {
      //   this.mapLayer.drawVectorLayer = this.hiMap.createUserLayer('draw', {wrapX: false}, {});
      // }
      if (!this.mapLayer.markerVectorLayer) {
        this.mapLayer.markerVectorLayer = this.hiMap.createUserLayer(
          "marker",
          {},
          {}
        );
      }
    },
    /**
     *
     * @Description: 初始化页面
     * @Author: 王燕欣
     * @Date: 2024-10-09 17:59
     */
    pageInit() {
      if (this.startTimeUrl && this.endTimeUrl) {
        console.log('路由有参数状态---startTimeUrl-', this.startTimeUrl);
        console.log('路由有参数状态---endTimeUrl-', this.endTimeUrl);
        this.queryDateStr = dayjs(this.startTimeUrl).format("YYYY-MM-DD");
        this.queryTime = {
          start: dayjs(this.startTimeUrl).format("HH:mm:ss"),
          end: dayjs(this.endTimeUrl).format("HH:mm:ss"),
        };
      } else {
        this.queryDateStr = dayjs().format("YYYY-MM-DD");
        this.queryTime = {
          start: dayjs().subtract(1, "hour").format("HH:mm:ss"),
          end: dayjs().format("HH:mm:ss"),
        };
      }

      // 初始化查询
      this.trackPlayer.busIdList = [];
      this.trackPlayer.currentTime =
        this.queryDateStr + "" + this.queryTime.start;
    },
    /**
     * @Description: 获取有权限的线路列表
     * @Author: 王燕欣
     * @Date: 2024-09-27 11:17
     */
    async getAuthRouteListFun() {
      const prames = {};
      await getAuthRouteListApi(prames).then((res) => {
        console.log("获取有权限的线路列表---", res);
        this.routerList = res.data;
        this.activeRouterIndex = 0;
        try {
          if (!this.routeParamState) {
            this.trackRouterId = res.data[0].routeId;
          }
          this.getBusListByRouteIdFun()
        } catch (error) {
          console.warn("打印error", error);
        }
      });
    },
    // 点击线路事件
    selectRouterClick(param) {
      this.clearAllLayer();
      this.trackRouterId = param;
      this.getBusListByRouteIdFun()
    },

    /**
    * @Description: 根据线路id 获取车辆列表
    * @Author: 王燕欣
    * @Date: 2024-10-16 13:17
    */
    async getBusListByRouteIdFun() {

      const prames = {
        endTime: this.queryDateStr + " " + this.queryTime.end,
        routeId: this.trackRouterId,
        startTime: this.queryDateStr + " " + this.queryTime.start,
      };
      await getHistoryBusListByRouteApi(prames).then((res) => {
        // console.log("选择线路查询车辆列表---", res);
        // 处理数据中有busId为空的数据
        this.trackRouterBusList = res.data.filter((item) => {
          return item.busId;
        })
      });
      this.getRouteStationLineFun();
      if (this.routeParamState) {
        this.selectBusClick(this.trackBusId)
      }

    },


    /**
    * @Description: 显示线路车辆列表
    * @Author: 王燕欣
    * @Date: 2024-10-14 10:01
    */
    lineBusShowStateClick() {
      this.lineBusShowState = !this.lineBusShowState;
    },

    /**
     * @Description: 选择车辆事件
     * @Author: 王燕欣
     * @Date: 2024-10-08 17:57
     */
    selectBusClick(prame) {
      this.mapLayer.trackVectorLayer.getSource().clear();
      this.mapLayer.speedVectorLayer.getSource().clear();
      this.mapLayer.busVectorLayer.getSource().clear();

      this.trackPlayer.currentStep = 0;
      this.trackBusId = prame;
      this.trackPlayer.busIdList = [prame];

      this.lineBusShowState = false; // 关闭选择车辆
      this.trackBusInfo = this.trackRouterBusList.filter((item) => {
        return prame === item.busId;
      })[0];
      console.log('选择车辆事件---车辆详情', this.trackBusInfo);
      this.getHistoryInfoByBusList();
    },
    /**
     * @Description: 获取历史轨迹
     * @Author: 王燕欣
     * @Date: 2024-10-08 17:57
     */
    getHistoryInfoByBusList() {
      let _this = this;
      this.searchDisabled = true;
      _this.tableData = [];

      if (!this.trackBusId) {
        Toast.fail("请选择车辆");
        return;
      }
      const prames = {
        busIdList: [this.trackBusId],
        endTime: this.queryDateStr + " " + this.queryTime.end,
        startTime: this.queryDateStr + " " + this.queryTime.start,
        sysCode: "FDIS",
      };
      getHistoryInfoByBusListApi(prames)
        .then((res) => {
          console.log('获取历史轨迹----res---', res)
          if (res.data && res.data.length > 0) {
            _this.trackSubRouteId = res.data[0].subRouteId;
            _this.drawSubRouteFeature();
            _this.tableData = res.data.map((row, index) => {
              if (index === 0) {
                row.totalGpsMile = 0;
              } else {
                row.totalGpsMile = res.data[index - 1].totalGpsMile;
                let tmpSecond =
                  new Date(row.actDateTime) -
                  new Date(res.data[index - 1].actDateTime);
                let tmpGpsMile = row.gpsMile - res.data[index - 1].gpsMile;
                if (
                  !(
                    row.gpsMile < 0 ||
                    (tmpSecond === 0 && tmpGpsMile > 0) ||
                    (tmpGpsMile / (tmpSecond == 0 ? 1 : tmpSecond)) * 3.6 > 100
                  ) &&
                  tmpGpsMile > 0
                ) {
                  row.totalGpsMile = row.totalGpsMile + tmpGpsMile;
                }
              }
              return row;
            });
            _this.trackPlayer.busIdList = [res.data[0].busId];
            let firstData = _this.tableData.find(
              (row) => row.gpsLong > 5 && row.gpsLat > 5
            );
            _this.hiMap.map
              .getView()
              .setCenter(
                this.hiMap.transform([firstData.gpsLong, firstData.gpsLat])
              );
            _this.setAlertEvents(); // 获取异常事件标记
            _this.playTrack();
          } else {
            console.log("暂无轨迹数据");
            Toast("暂无轨迹数据");
            window.clearInterval(_this.trackPlayer.playInterval);
            this.trackPlayer.currentStep = 0;
          }
          this.searchDisabled = false;
        })
        .catch((err) => {
          console.log("获取轨迹数据错误----", err);
          this.searchDisabled = false;
        });
    },
    /**
     * 进度调整
     * @param value
     */
    changeStep(value) {
      this.trackPlayer.currentTime = dayjs(
        new Date(this.queryDateStr + " " + this.queryTime.start).getTime() +
        this.trackPlayer.stepSecond * value * 1000
      ).format("YYYY-MM-DD HH:mm:ss");
      // this.formatTooltip(value);
      if (this.tableData.length > 0) {
        // this.addDataToTable();
        this.addTrackLine();
        // this.addPeccancyFeature();
      }
    },

    /**
     * @Description: 显示运行数据
     * @Author: 王燕欣
     * @Date: 2024-10-10 10:34
     */
    showOperationalDataClick() {
      this.$refs.TablePopupRef.showModule();
    },
    /**
     * @Description: 是否显示线路站点事件
     * @Author: 王燕欣
     * @Date: 2024-09-27 15:55
     */
    showStationStatusClick() {
      this.lineVectorLayerConfig.stationStatus =
        !this.lineVectorLayerConfig.stationStatus;
      this.drawSubRouteFeature();
    },
    /**
     * @Description: 是否显示速度事件
     * @Author: 王燕欣
     * @Date: 2024-09-27 15:55
     */
    showSpeedStatusClick() {
      this.overlayCtrl.timeSpeedChecked = !this.overlayCtrl.timeSpeedChecked;
      if (!this.overlayCtrl.timeSpeedChecked) {
        this.mapLayer.speedVectorLayer.getSource().clear();
      } else {
        this.mapLayer.speedVectorLayer.getSource().addFeatures(this.overlayCtrl.speedVectorLayerObject); // 绘制速度图层
      }
    },


    /**
     * @Description: 获取线路站点信息
     * @Author: 王燕欣
     * @Date: 2024-09-29 13:22
     */
    async getRouteStationLineFun() {
      this.mapLayer.lineVectorLayer.getSource().clear();

      // 获取线路站点
      await getRouteStationLineApi({
        routeId: this.trackRouterId
      }).then((res) => {
        this.routeRelationList = res.data;

      });
    },

    /**
     * @Description: 绘制标准轨迹
     * @Author: 王燕欣
     * @Date: 2024-10-10 17:14
     */
    /**
      * 绘制标准---轨迹
      */
    drawSubRouteFeature() {
      console.log('绘制标准---轨迹----trackRouterId---', this.trackRouterId)
      console.log('绘制标准---轨迹----routeRelationList---', this.routeRelationList)
      // 清空已绘制轨迹车辆标记
      this.mapLayer.lineVectorLayer.getSource().clear();

      if (!this.trackRouterId || this.routeRelationList.length === 0) return;
      let _this = this;
      let lineStringDown = [], stationListDown = [], stationIdsDown = [], routeLineIds = [];
      let lineStringUp = [], stationListUp = [], stationIdsUp = [];


      // 上下行 
      // 
      this.routeRelationList.forEach(route => {
        if (route.subRouteList && route.subRouteList.length > 0) {
          route.subRouteList.forEach(subRoute => {
            if (this.trackSubRouteId === subRoute.subRouteId) {
              subRoute.segmentList.forEach(segment => {
                routeLineIds.push(segment.segmentId);
                if (segment.runDirection === '1') {
                  segment.stationList.forEach((station) => {

                    if (station.serialCode === 1) {
                      station.isStart = true;
                    }
                    if (station.serialCode === _this.routeRelationList.length) {
                      station.isEnd = true;
                    }
                    lineStringDown.push([station.longitude, station.latitude]);
                    stationListDown.push(station);
                    stationIdsDown.push(station.rSegmentSId);
                    let jwd = _this.transStrToArray(station.jwd);
                    lineStringDown = lineStringDown.concat(jwd);
                  })
                } else {
                  segment.stationList.forEach((station) => {

                    if (station.serialCode === 1) {
                      station.isStart = true;
                    }
                    if (station.serialCode === _this.routeRelationList.length) {
                      station.isEnd = true;
                    }
                    lineStringUp.push([station.longitude, station.latitude]);
                    stationListUp.push(station);
                    stationIdsUp.push(station.rSegmentSId);
                    let jwd = _this.transStrToArray(station.jwd);
                    lineStringUp = lineStringUp.concat(jwd);
                  })
                }
              })
            }

          })
        }
      });
      if (lineStringDown.length > 0) {
        _this.addRouteLine(routeLineIds[0], lineStringDown, stationListDown);
      }
      if (lineStringUp.length > 0) {
        _this.addRouteLine(routeLineIds[1], lineStringUp, stationListUp);
      }
    },
    /**
    * @Description: 经纬对字符串转数组
    * @Author: 王燕欣
    * @Date: 2024-10-17 17:25
    */
    transStrToArray(str) {
      let array = [];
      if (!str) {
        return array;
      }
      array = str.split(";");
      for (let i = 0, len = array.length; i < len; i++) {
        if (array[i]) {
          array[i] = array[i].split(',');
        }
      }
      return array;
    },
    /**
 * 添加线路轨迹
 * @param coordinates
 * @param config
 */
    addRouteLine(segmentId, lineCoordinates, stationList) {
      console.log('stationList---添加线路轨迹--->', stationList);

      let featureArray = [];
      // 线路
      let transCoordinates = [];
      for (let i = 0; i < lineCoordinates.length; i++) {
        transCoordinates.push(this.hiMap.transform(lineCoordinates[i]));
      }
      let lineString = new LineString(transCoordinates);
      let lineFeature = new Feature({
        geometry: lineString
      });
      lineFeature.setId(segmentId);
      lineFeature.setStyle(
        new Style({
          stroke: new Stroke({
            width: 4,
            color: 'rgba(66, 81, 223, 0.7)'
          }),
        })
      );
      featureArray.push(lineFeature);
      // 绘制起点站
      let startMaker = new Feature({
        type: 'icon',
        geometry: new Point(lineString.getFirstCoordinate()),
      });
      startMaker.setId(segmentId + '-start');
      startMaker.setStyle(
        new Style({
          image: new Icon({
            displacement: [0, 18],
            src: require("@/assets/images/gis/StartPoint.png")
          }),
          text: new Text({
            text: '起',
            textAlign: 'center',
            font: 'bold 12px 宋体',
            fill: new Fill({ color: '#13CD68' }),
            offsetX: 0,
            offsetY: -23
          })
        })
      );
      featureArray.push(startMaker);
      // 绘制终点站
      let endMaker = new Feature({
        geometry: new Point(lineString.getLastCoordinate()),
      });
      endMaker.setId(segmentId + '-end');
      endMaker.setStyle(
        new Style({
          image: new Icon({
            displacement: [0, 18],
            src: require("@/assets/images/gis/EndPoint.png")
          }),
          text: new Text({
            text: '终',
            textAlign: 'center',
            font: 'bold 12px 宋体',
            fill: new Fill({ color: '#FF5353' }),
            offsetX: 0,
            offsetY: -23
          })
        })
      );
      featureArray.push(endMaker);


      for (let i = 0; i < stationList.length; i++) {
        let featureId = stationList[i].rSegmentSId || (segmentId + '-' + stationList[i].stationId);
        let stationInfo = stationList[i];
        let coordinate = this.hiMap.transform([stationInfo.longitude, stationInfo.latitude]);
        let feature = new Feature({
          geometry: new Point(coordinate),
        });
        feature.setId(featureId);
        let imageStyle = new CircleStyle({
          radius: 6,
          fill: new Fill({
            color: "#ffffff",
          }),
          stroke: new Stroke({
            color: "#4251DF",
            width: 1,
          }),
        });
        let textStyle = new Text({
          textAlign: "left",
          font: "12px 宋体",
          style: {
            fontWeight: "bold", // 设置加粗
          },
          // text: stationInfo.serialCode + "-" + stationInfo.stationName,
          text: stationInfo.stationName, // 站点名称
          fill: new Fill({
            color: "#212121",
          }),
          padding: [5, 7, 5, 7],
          offsetX: 10,
          offsetY: 0,
          maxAngle: 0,
          rotation: 0,
        });
        if (this.lineVectorLayerConfig.stationStatus) {
          feature.setStyle(
            new Style({
              image: imageStyle,
              text: textStyle
            })
          );
        }
        else {
          feature.setStyle(
            new Style({
              image: imageStyle
            })
          );
        }
        featureArray.push(feature);
      }

      this.hiMap.map.getView().setCenter(lineCoordinates[0]); // 设置中心点
      this.mapLayer.lineVectorLayer.getSource().addFeatures(featureArray);
    },

    /**
     * @Description: 添加运行轨迹
     * @Author: 王燕欣
     * @Date: 2024-10-10 18:24
     */
    addTrackLine() {
      this.mapLayer.trackVectorLayer.getSource().clear();
      this.mapLayer.speedVectorLayer.getSource().clear();

      this.mapLayer.busVectorLayer.getSource().clear();
      if (this.trackPlayer.busIdList.length === 0) return;
      let trackList = [],
        busList = [],
        speedList = [];
      for (let i = 0; i < this.trackPlayer.busIdList.length; i++) {
        if (!this.trackPlayer.busIdList[i]) continue;
        let gpsList = this.tableData.filter(
          (row) =>
            row.busId === this.trackPlayer.busIdList[i] &&
            new Date(row.actDateTime) <= new Date(this.trackPlayer.currentTime)
        );
        if (gpsList.length === 0) continue;
        let coordinates = [];
        let busInfo = null;
        for (let i = 0; i < gpsList.length; i++) {
          if (gpsList[i].gpsLong < 5 || gpsList[i].gpsLat < 5) continue;
          coordinates.push(
            this.hiMap.transform([gpsList[i].gpsLong, gpsList[i].gpsLat])
          );
          this.hiMap.map.getView().setCenter([gpsList[i].gpsLong, gpsList[i].gpsLat]); // 设置中心点
          busInfo = gpsList[i];
        }
        let feature = new Feature({
          geometry: new LineString(coordinates),
        });
        feature.setId(this.trackPlayer.busIdList[i]);
        feature.setStyle(
          new Style({
            stroke: new Stroke({
              width: 3,
              color: this.busColorList[i % this.busColorList.length],
            }),
          })
        );
        trackList.push(feature);
        let longitude = busInfo.gpsLong || 0;
        let latitude = busInfo.gpsLat || 0;
        let coordinate = this.hiMap.transform([longitude, latitude]);
        let busFeature = new Feature({
          geometry: new Point(coordinate),
        });
        busFeature.setId(busInfo.busId);
        busFeature.set("data", busInfo);
        let angle = busInfo.gpsAngle || 0;
        if (this.overlayCtrl.timeSpeedChecked) {
          busFeature.setStyle(
            new Style({
              image: new Icon({
                img: this.drawBusImage(
                  angle,
                  this.locatedBusId === busInfo.busId,
                  busInfo
                ),
                imgSize: [52, 52],
              }),
            })
          );
        } else {
          busFeature.setStyle(
            new Style({
              image: new Icon({
                img: this.drawBusImage(
                  angle,
                  this.locatedBusId === busInfo.busId,
                  busInfo
                ),
                imgSize: [52, 52],
              }),
            })
          );
        }
        busList.push(busFeature);

        // 绘制运行速度图层
        let speedFeature = new Feature({
          geometry: new Point(coordinate),
        });
        speedFeature.setId(busInfo.busId);
        speedFeature.set("data", busInfo);
        if (this.overlayCtrl.timeSpeedChecked) {
          speedFeature.setStyle(
            new Style({
              image: new Icon({
                img: this.drawBusSpeedImage(busInfo), // 绘制速度内容
                imgSize: [146, 66],
                offset: [-26, 0],
                anchorXUnits: 120,
              }),
            })
          );
        }
        speedList.push(speedFeature);
        if (this.trackPlayer.busIdList.length == 1) {
          this.checkFeatureInView([longitude, latitude]);
        }
      }
      if (trackList.length > 0) {
        this.mapLayer.trackVectorLayer.getSource().addFeatures(trackList);
        this.mapLayer.speedVectorLayer.getSource().addFeatures(speedList); // 绘制速度图层
        this.overlayCtrl.speedVectorLayerObject = speedList;

        this.mapLayer.busVectorLayer.getSource().addFeatures(busList);
      }
    },
    /**
     * 绘制车辆图标
     */
    drawBusImage(rotate, isLocated, busInfo) {
      const canvas = document.createElement("canvas"); //document.querySelector("#realtimeMonitorBusCanvas");
      canvas.width = 52;
      canvas.height = 52;
      const ctx = canvas.getContext("2d");
      if (isLocated) {
        const img3 = document.querySelector("#realtimeMonitorBusLocatedIcon");
        if (img3) {
          ctx.drawImage(img3, 0, 0);
        }
      }
      let imgSelector = "realtimeMonitorBusDirection";
      // 违规
      if (busInfo && busInfo.busViolate === "1") {
        imgSelector = "realtimeMonitorBusPeccancyDirection";
      }
      const img = document.querySelector("#" + imgSelector);
      if (img) {
        // img.setAttribute('crossOrigin', 'Anonymous');
        // 平移转换，改变画笔的原点位置为画布的中心点
        ctx.translate(canvas.width / 2, canvas.height / 2);
        // 旋转转换，改变画笔的旋转角度
        ctx.rotate((rotate * Math.PI) / 180);
        // 调用绘制图片的方法把图片绘制到canvas中
        ctx.drawImage(img, -img.width / 2, -img.height / 2);
        // 还原坐标系
        ctx.translate(0, 0);
        ctx.rotate(-rotate * (Math.PI / 180));
        // 使用 restore()进行恢复
        ctx.restore();
      }
      const img2 = document.querySelector("#realtimeMonitorBusIcon");
      if (img2) {
        ctx.drawImage(img2, -img2.width / 2, -img2.height / 2);
      }
      // 非营运
      if (busInfo && busInfo.busStatus === "5") {
        // let runTypeObj = this.searchRunTypeList.find(item => item.itemValue === busInfo.busOperateCondType);
        // if (runTypeObj && runTypeObj.itemKeySimple) {
        //   ctx.beginPath();
        //   ctx.fillStyle = '#58B02B';
        //   ctx.strokeStyle = '#58B02B';
        //   ctx.lineJoin = 'round';  //交点设置成圆角
        //   ctx.lineWidth = 4;
        //   ctx.strokeRect(4, -20, 14, 14);
        //   ctx.fillRect(6, -18, 12, 12);
        //   ctx.stroke();
        //   ctx.closePath();
        //   ctx.font = '14px 微软雅黑';
        //   ctx.fillStyle = '#fff';
        //   ctx.fillText(runTypeObj.itemKeySimple, 4, -8);
        // }
      }
      return canvas;
    },

    drawBusSpeedImage(busInfo) {
      // console.log("busInfo---", busInfo);
      const canvas = document.getElementById("canvasSpeed");
      canvas.style.imageRendering = 'optimizeQuality'; // 针对Webkit浏览器（如Chrome）
      canvas.width = 126;
      canvas.height = 66;
      const ctx = canvas.getContext("2d");
      // 绘制背景
      ctx.fillStyle = "#ffffff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      let busSpeed = parseInt(busInfo.busSpeed) + '' || 0 + '';

      // 速度 65
      ctx.fillStyle = "#01AA59";
      ctx.font = "22px DINPro";
      ctx.fontWeight = 'bold';
      ctx.textAlign = "left";
      ctx.textBaseline = "top"; // 文字基线
      ctx.fillText(`${busSpeed}`, 15, 12);

      // 计算单位X轴位置
      let speedUnitX = 22;
      if (busSpeed.length > 1) {
        speedUnitX = busSpeed.length * 22;
      } else {
        speedUnitX = 32;
      }

      //速度单位
      ctx.fillStyle = "#444444";
      ctx.font = "12px DINPro";
      ctx.textAlign = "left";
      ctx.textBaseline = "top"; // 文字基线
      ctx.fillText(`${busInfo.busSpeedUnit || "km/h"}`, speedUnitX, 20);


      // 绘制下边内容 16:45:59
      ctx.fillStyle = "#222222";
      ctx.fontWeight = '500';
      ctx.font = "15px DINPro";
      ctx.textAlign = "left";
      ctx.textBaseline = "top"; // 文字基线
      ctx.fillText(`${busInfo.actDateTime.split(' ')[1] || "--:--:--"}`, 15, 40);

      return canvas;
    },

    /**
     * @Description: 检查车辆图标是否超出可视范围
     * @Author: 王燕欣
     * @Date: 2024-10-11 10:36
     */

    checkFeatureInView: function ([lng, lat]) {
      let viewArea = this.hiMap.map
        .getView()
        .calculateExtent(this.hiMap.map.getSize());
      let coordinate = this.hiMap.transform([lng, lat]);
      if (
        coordinate[0] <= Math.min(viewArea[0], viewArea[2]) ||
        coordinate[0] >= Math.max(viewArea[0], viewArea[2]) ||
        coordinate[1] <= Math.min(viewArea[1], viewArea[3]) ||
        coordinate[1] >= Math.max(viewArea[1], viewArea[3])
      ) {
        this.hiMap.map.getView().setCenter(coordinate);
      }
    },

    /**
    * @Description: 清除图层
    * @Author: 王燕欣
    * @Date: 2025-01-06 17:14
    */
    clearAllLayer() {
      this.tableData = [];
      this.mapLayer.trackVectorLayer.getSource().clear(); // 运行轨迹图层
      this.mapLayer.lineVectorLayer.getSource().clear(); // 线路轨迹图层
      this.mapLayer.busVectorLayer.getSource().clear(); // 车辆图层
      this.mapLayer.speedVectorLayer.getSource().clear(); // 速度图层
      this.mapLayer.peccancyVectorLayer.getSource().clear(); // 违规告警图层
    },


    /**
    * @Description: 选择年月
    * @Author: 王燕欣
    * @Date: 2025-01-03 14:47
    */
    datePickerPopupClick() {
      this.$refs.DatetimePickerRef.showModule(this.queryDateStr);
    },

    /**
     * @Description: 选择年月日时间
     * @Author: 王燕欣
     * @Date: 2024-10-08 14:15
     */
    datetimePickerPopupClick() {
      this.$refs.datetimePickerPopupRef.showModule();
    },

    // 确认选择日期
    onConfirmDate(date) {
      this.dateShow = false;
      this.queryDateStr = dayjs(date).format("YYYY-MM-DD");
      this.getHistoryInfoByBusList();
    },
    /**
     * @Description: 选择时间区域
     * @Author: 王燕欣
     * @Date: 2024-10-08 14:58
     */
    datetimeOnConfirm(params) {
      this.queryTime = params;
      this.getHistoryInfoByBusList();
    },
    /**
    * @Description: 获取异常事件标记
    * @Author: 王燕欣
    * @Date: 2024-10-14 13:29
    */
    setAlertEvents() {
      console.log('获取异常事件标记')

      this.trackPlayer.alertEvents = {};
      let alertData = this.tableData.filter(row => row.dataType === '55');
      console.log('违规信息---alertData--row.dataType === 55---', alertData)
      // 处理违规数据 在滑动条上增加


      // for (let i = 0, len = alertData.length; i < len; i++) {
      //   let actDateTime = alertData[i].actDateTime;
      //   let step = Math.ceil((new Date(actDateTime) - new Date(this.queryDateStr + ' ' + this.queryTime.start)) / 1000 / this.trackPlayer.secondStep);

      //   this.trackPlayer.alertEvents[step] = {
      //     style: {
      //       color: 'red'
      //     },
      //     data: alertData[i]
      //   }
      // }
      this.$nextTick(() => {
        console.log('违规信息--list---', this.trackPlayer.alertEvents)
        // let domList = document.querySelectorAll(".el-slider__stop");
        // let stepIndex = 0;
        // for (const step in this.trackPlayer.alertEvents) {
        //   domList[stepIndex].title = this.trackPlayer.alertEvents[step].data.infoType;
        //   stepIndex++;
        // }
      })
    },

    /**
     * @Description: 滑块滑动方法
     * @Author: 王燕欣
     * @Date: 2024-10-09 13:27
     */
    onChangeSlider(value) {
      console.log("滑块滑动方法----", value);
      this.trackPlayer.currentStep = value;
      this.changeStep(value);
      this.pauseTrack();

      // 提示用户滑动的位置
      this.trackPlayer.currentTime = dayjs(
        new Date(this.queryDateStr + " " + this.queryTime.start).getTime() +
        this.trackPlayer.stepSecond * value * 1000
      ).format("YYYY-MM-DD HH:mm:ss");
      Toast({
        message: this.trackPlayer.currentTime.split(' ')[1],
        position: 'bottom',
      });

      if (this.trackPlayer.maxStep === value) {
        this.trackPlayer.isPlaying = false;
      }
    },

    /**
     * @Description: 播放
     * @Author: 王燕欣
     * @Date: 2024-10-11 09:38
     */
    playTrack() {
      let _this = this;
      if (this.tableData.length === 0) {
        // console.log("暂无轨迹数据");
        Toast('暂无轨迹数据')
        return;
      }
      if (this.trackPlayer.currentStep === this.trackPlayer.maxStep) {
        this.trackPlayer.currentStep = 0;
        this.table = [];
      }
      this.trackPlayer.isPlaying = true;
      if (this.trackPlayer.playInterval) {
        window.clearInterval(this.trackPlayer.playInterval);
        this.trackPlayer.playInterval = null;
      }

      this.trackPlayer.playInterval = window.setInterval(function () {
        if (_this.trackPlayer.currentStep < _this.trackPlayer.maxStep) {
          _this.trackPlayer.currentStep++;
          _this.changeStep(_this.trackPlayer.currentStep);
        } else {
          window.clearInterval(_this.trackPlayer.playInterval);
          _this.trackPlayer.playInterval = null;
          _this.trackPlayer.isPlaying = false;
        }
      }, 1000 / _this.trackPlayer.playSpeed);
    },
    /**
     * @Description: 暂停
     * @Author: 王燕欣
     * @Date: 2024-10-11 09:38
     */
    pauseTrack() {
      this.trackPlayer.isPlaying = false;
      window.clearInterval(this.trackPlayer.playInterval);
      this.trackPlayer.playInterval = null;
    },
    /**
     * @Description: 后退
     * @Author: 王燕欣
     * @Date: 2024-10-11 09:38
     */
    playPrevTrack() {
      this.trackPlayer.isPlaying = false;
      this.trackPlayer.currentStep =
        this.trackPlayer.currentStep < this.trackPlayer.moveStep
          ? this.trackPlayer.minStep
          : this.trackPlayer.currentStep - this.trackPlayer.moveStep;
      this.changeStep(this.trackPlayer.currentStep);
    },
    /**
     * @Description: 前进
     * @Author: 王燕欣
     * @Date: 2024-10-11 09:38
     */
    playNextTrack() {
      this.trackPlayer.isPlaying = false;
      this.trackPlayer.currentStep =
        this.trackPlayer.currentStep + this.trackPlayer.moveStep >
          this.trackPlayer.maxStep
          ? this.trackPlayer.maxStep
          : this.trackPlayer.currentStep + this.trackPlayer.moveStep;
      this.changeStep(this.trackPlayer.currentStep);
    },
    /**
     * @Description: 播放速度变更
     * @Author: 王燕欣
     * @Date: 2024-10-11 09:38
     */
    playSpeedClick(param) {
      this.playSpeedShow = false;
      this.trackPlayer.playSpeed = param;
      if (this.trackPlayer.playInterval) {
        clearInterval(this.trackPlayer.playInterval);
        this.trackPlayer.playInterval = null;
      }
      if (this.trackPlayer.isPlaying) {
        this.playTrack();
      }
    },
  },
};
</script>
<style lang="sass" scoped>
</style>
